'use client';

import React, {useState, useMemo, useEffect} from 'react';
import {motion} from 'framer-motion';
import {
    CalendarDaysIcon,
    ClockIcon,

} from '@heroicons/react/24/outline';
import {useAppStore} from '@/store';
import type {Activity} from '@/types';
import {formatDate, formatTime, formatCoinChange} from '@/utils';
import Card, {CardHeader, CardTitle, CardContent} from '@/components/ui/Card';

interface DateRange {
    start: Date;
    end: Date;
    label: string;
}

const TimeBoard: React.FC = () => {
    const {activities} = useAppStore();
    const [selectedDateRange, setSelectedDateRange] = useState<DateRange | null>(null);
    const [customRange, setCustomRange] = useState<{ start: string; end: string }>({
        start: '',
        end: ''
    });
    const [isClient, setIsClient] = useState(false);

    // 确保在客户端环境下运行
    useEffect(() => {
        setIsClient(true);
        const today = new Date();
        const weekAgo = new Date(today);
        weekAgo.setDate(today.getDate() - 6);
        setSelectedDateRange({
            start: weekAgo,
            end: today,
            label: '最近7天'
        });
    }, []);

    // 预设时间范围
    const presetRanges = useMemo(() => {
        if (!isClient) return [];

        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(today.getDate() - 1);

        const weekAgo = new Date(today);
        weekAgo.setDate(today.getDate() - 6);

        const monthAgo = new Date(today);
        monthAgo.setDate(today.getDate() - 29);

        const threeMonthsAgo = new Date(today);
        threeMonthsAgo.setMonth(today.getMonth() - 3);

        return [
            {
                start: today,
                end: today,
                label: '今天'
            },
            {
                start: yesterday,
                end: yesterday,
                label: '昨天'
            },
            {
                start: weekAgo,
                end: today,
                label: '最近7天'
            },
            {
                start: monthAgo,
                end: today,
                label: '最近30天'
            },
            {
                start: threeMonthsAgo,
                end: today,
                label: '最近3个月'
            }
        ];
    }, [isClient]);

    // 筛选指定时间范围内的活动
    const filteredActivities = useMemo(() => {
        if (!selectedDateRange) return [];

        return activities.filter(activity => {
            const timestamp = activity.timestamp instanceof Date
                ? activity.timestamp
                : new Date(activity.timestamp);

            const activityDate = new Date(timestamp.getFullYear(), timestamp.getMonth(), timestamp.getDate());
            const startDate = new Date(selectedDateRange.start.getFullYear(), selectedDateRange.start.getMonth(), selectedDateRange.start.getDate());
            const endDate = new Date(selectedDateRange.end.getFullYear(), selectedDateRange.end.getMonth(), selectedDateRange.end.getDate());

            return activityDate >= startDate && activityDate <= endDate;
        });
    }, [activities, selectedDateRange]);

    // 按日期分组的活动
    const activitiesByDate = useMemo(() => {
        const grouped = new Map<string, Activity[]>();

        filteredActivities.forEach(activity => {
            const timestamp = activity.timestamp instanceof Date
                ? activity.timestamp
                : new Date(activity.timestamp);

            const dateKey = timestamp.toISOString().split('T')[0];
            if (!grouped.has(dateKey)) {
                grouped.set(dateKey, []);
            }
            grouped.get(dateKey)!.push(activity);
        });

        // 按时间排序
        grouped.forEach((activitiesInDate) => {
            activitiesInDate.sort((a, b) => {
                const timeA = a.timestamp instanceof Date ? a.timestamp : new Date(a.timestamp);
                const timeB = b.timestamp instanceof Date ? b.timestamp : new Date(b.timestamp);
                return timeA.getTime() - timeB.getTime();
            });
        });

        return grouped;
    }, [filteredActivities]);

    // 获取时间范围内的所有日期
    const datesInRange = useMemo(() => {
        if (!selectedDateRange) return [];

        const dates = [];
        const current = new Date(selectedDateRange.start);
        const end = new Date(selectedDateRange.end);

        while (current <= end) {
            dates.push(current.toISOString().split('T')[0]);
            current.setDate(current.getDate() + 1);
        }

        return dates.reverse(); // 最新的日期在前
    }, [selectedDateRange]);

    // 处理自定义时间范围
    const handleCustomRangeSubmit = () => {
        if (customRange.start && customRange.end) {
            const start = new Date(customRange.start);
            const end = new Date(customRange.end);

            if (start <= end) {
                setSelectedDateRange({
                    start,
                    end,
                    label: `${formatDate(start, 'M月d日')} - ${formatDate(end, 'M月d日')}`
                });
            }
        }
    };

    // 统计数据
    const stats = useMemo(() => {
        const totalActivities = filteredActivities.length;
        const totalCoins = filteredActivities.reduce((sum, a) => sum + a.coinChange, 0);
        const activeDays = new Set(filteredActivities.map(a => {
            const timestamp = a.timestamp instanceof Date ? a.timestamp : new Date(a.timestamp);
            return timestamp.toISOString().split('T')[0];
        })).size;

        return {
            totalActivities,
            totalCoins,
            activeDays
        };
    }, [filteredActivities]);

    // 在客户端水合完成前显示加载状态
    if (!isClient) {
        return (
            <div className="space-y-6">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900">时间看板</h1>
                    <p className="text-gray-600 mt-1">按时间维度查看你的活动记录</p>
                </div>
                <div className="text-center py-8 text-gray-500">
                    加载中...
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-6 h-full">
            <div>
                <h1 className="text-2xl font-bold text-gray-900">时间看板</h1>
                <p className="text-gray-600 mt-1">按时间维度查看你的活动记录</p>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 h-[calc(100vh-200px)]">
                {/* 时间范围选择器 */}
                <Card className="lg:col-span-1 flex flex-col">
                    <CardHeader className="flex-shrink-0">
                        <CardTitle className="flex items-center gap-2">
                            <CalendarDaysIcon className="w-5 h-5"/>
                            选择时间范围
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="flex-1 overflow-y-auto">
                        {/* 预设时间范围 */}
                        <div className="space-y-2">
                            <h4 className="text-sm font-medium text-gray-700">快速选择</h4>
                            {presetRanges.map((range, index) => (
                                <motion.button
                                    key={index}
                                    whileHover={{scale: 1.02}}
                                    whileTap={{scale: 0.98}}
                                    onClick={() => setSelectedDateRange(range)}
                                    className={`w-full p-3 rounded-lg text-left transition-all ${
                                        selectedDateRange?.label === range.label
                                            ? 'bg-blue-50 border border-blue-200'
                                            : 'hover:bg-gray-50 border border-gray-200'
                                    }`}
                                >
                                    <div className="font-medium text-sm text-gray-900">
                                        {range.label}
                                    </div>
                                    <div className="text-xs text-gray-500 mt-1">
                                        {range.start.getTime() === range.end.getTime()
                                            ? formatDate(range.start, 'M月d日')
                                            : `${formatDate(range.start, 'M月d日')} - ${formatDate(range.end, 'M月d日')}`
                                        }
                                    </div>
                                </motion.button>
                            ))}
                        </div>

                        {/* 自定义时间范围 */}
                        <div className="space-y-2 border-t pt-4">
                            <h4 className="text-sm font-medium text-gray-700">自定义范围</h4>
                            <div className="space-y-2">
                                <div>
                                    <label className="text-xs text-gray-500">开始日期</label>
                                    <input
                                        type="date"
                                        value={customRange.start}
                                        onChange={(e) => setCustomRange(prev => ({...prev, start: e.target.value}))}
                                        className="w-full p-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs text-gray-500">结束日期</label>
                                    <input
                                        type="date"
                                        value={customRange.end}
                                        onChange={(e) => setCustomRange(prev => ({...prev, end: e.target.value}))}
                                        className="w-full p-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                </div>
                                <button
                                    onClick={handleCustomRangeSubmit}
                                    disabled={!customRange.start || !customRange.end}
                                    className="w-full p-2 bg-blue-600 text-white rounded-md text-sm hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
                                >
                                    应用范围
                                </button>
                            </div>
                        </div>

                        {/* 统计信息 */}
                        {selectedDateRange && (
                            <div className="space-y-2 border-t pt-4">
                                <h4 className="text-sm font-medium text-gray-700">统计信息</h4>
                                <div className="space-y-1">
                                    <div className="flex justify-between text-sm">
                                        <span className="text-gray-600">活跃天数</span>
                                        <span className="font-medium">{stats.activeDays} 天</span>
                                    </div>
                                    <div className="flex justify-between text-sm">
                                        <span className="text-gray-600">总记录</span>
                                        <span className="font-medium">{stats.totalActivities} 条</span>
                                    </div>
                                    <div className="flex justify-between text-sm">
                                        <span className="text-gray-600">金币变化</span>
                                        <span
                                            className={`font-medium ${stats.totalCoins >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                      {stats.totalCoins > 0 ? '+' : ''}{stats.totalCoins}
                    </span>
                                    </div>
                                </div>
                            </div>
                        )}
                    </CardContent>
                </Card>

                {/* 活动时间线 */}
                <div className="lg:col-span-3">
                    <Card className="h-full flex flex-col">
                        <CardHeader className="flex-shrink-0">
                            <CardTitle className="flex items-center gap-2">
                                <ClockIcon className="w-5 h-5"/>
                                {selectedDateRange?.label} 活动时间线
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="flex-1 overflow-y-auto">
                            {filteredActivities.length > 0 ? (
                                <div className="space-y-6">
                                    {datesInRange.map(date => {
                                        const dayActivities = activitiesByDate.get(date) || [];
                                        if (dayActivities.length === 0) return null;

                                        const coinTotal = dayActivities.reduce((sum, a) => sum + a.coinChange, 0);

                                        return (
                                            <motion.div
                                                key={date}
                                                initial={{opacity: 0, y: 20}}
                                                animate={{opacity: 1, y: 0}}
                                                className="space-y-3"
                                            >
                                                {/* 日期标题 */}
                                                <div className="flex items-center gap-3 pb-2 border-b border-gray-200">
                                                    <h3 className="font-semibold text-gray-900">
                                                        {formatDate(new Date(date), 'M月d日 EEEE')}
                                                    </h3>
                                                    <div className="flex items-center gap-2 text-sm text-gray-500">
                                                        <span>{dayActivities.length} 条记录</span>
                                                        {coinTotal !== 0 && (
                                                            <span
                                                                className={`font-medium ${coinTotal > 0 ? 'text-green-600' : 'text-red-600'}`}>
                                {coinTotal > 0 ? '+' : ''}{coinTotal} 金币
                              </span>
                                                        )}
                                                    </div>
                                                </div>

                                                {/* 该日期的活动列表 */}
                                                <div className="space-y-2 pl-4">
                                                    {dayActivities.map((activity) => {
                                                        const coinChange = formatCoinChange(activity.coinChange);
                                                        const timestamp = activity.timestamp instanceof Date
                                                            ? activity.timestamp
                                                            : new Date(activity.timestamp);

                                                        return (
                                                            <motion.div
                                                                key={activity.id}
                                                                initial={{opacity: 0, x: -10}}
                                                                animate={{opacity: 1, x: 0}}
                                                                className="flex items-center gap-4 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                                                            >
                                                                <div className="text-sm text-gray-500 w-16">
                                                                    {formatTime(timestamp)}
                                                                </div>

                                                                <div className="flex-1">
                                                                    <h4 className="font-medium text-gray-900">{activity.title}</h4>
                                                                    {activity.content && (
                                                                        <p className="text-sm text-gray-600 mt-1">{activity.content}</p>
                                                                    )}
                                                                </div>

                                                                <div className="flex items-center gap-2">
                                                                    <span className="text-lg">{activity.mood}</span>
                                                                    <div
                                                                        className={`text-sm font-semibold px-2 py-1 rounded ${coinChange.color}`}>
                                                                        {coinChange.sign}{coinChange.text}
                                                                    </div>
                                                                </div>
                                                            </motion.div>
                                                        );
                                                    })}
                                                </div>
                                            </motion.div>
                                        );
                                    })}
                                </div>
                            ) : (
                                <div className="text-center py-12 text-gray-500">
                                    <CalendarDaysIcon className="w-12 h-12 mx-auto mb-4 text-gray-300"/>
                                    <p>这一天还没有活动记录</p>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </div>
            </div>
        </div>
    );
};

export default TimeBoard;